using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Configuration;
using System.Globalization;
using System.Text;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using IWCommunity.Common;

namespace IWCommunity.Blogs.WebControls
{
    /// <summary>
    /// Designed to return list of all discussion lists from current Web.
    /// </summary>
    public class RollUpList : List
    {
        private List<SPWeb> _availableWebs; //list to hold webs to iterate
        private string[] _sitesList;
        private DataTable _dtItems; //table to hold the items to display
        private int _iTotalThreads = 0;
        private int _iTotalPosts = 0;
        private int _iTotalUsers = 0;
        private int _iTotalArtifacts = 0;
        private int _iTotalSites = 0;
                                                

        private bool _IncludeSubsites = false;
        public bool IncludeSubsites
        {
            get { return _IncludeSubsites; }
            set { _IncludeSubsites = value; }
        }


        private int _maxSiteDepth = 1;
        public int MaxSiteDepth
        {
            get { return _maxSiteDepth; }
            set { _maxSiteDepth = value; }
        }

        
        private int _maxDisplayItems = 5;
        public int MaxDisplayItems
        {
            get { return _maxDisplayItems; }
            set { _maxDisplayItems = value; }
        }

        private string _sites = string.Empty;
        public string Sites
        {
            get
            {
                return _sites;
            }
            set
            {
                if (value != null)
                {
                    _sites = value;
                    _sitesList = _sites.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }
            }
        }

        private ReportViewType _reportView = ReportViewType.LatestPosts;
        public ReportViewType ReportView
        {
            get { return _reportView; }
            set { _reportView = value; }
        }

        public RollUpList()
        {
            _availableWebs = new List<SPWeb>();
            _dtItems = CreateDataTable();
        }

      

        protected override XmlDocument BuildDocument()
        {
            try
            {

                XmlDocument oDoc;               

                this.CreateAvailableWebsList(SPContext.Current.Site);

                if (_availableWebs.Count > 0)
                {
                    DataRow[] drItems = null;

                    switch (this.ReportView)
                    {

                        case ReportViewType.LatestPosts:
                            drItems = this.GetLatestPosts();
                            if ((drItems != null) && (drItems.Length > 0))
                                oDoc = GenerateOutput(drItems, false);
                            else
                                oDoc  = GenerateDefaultOutput();
                            break;
                        case ReportViewType.LatestUnansweredDiscussionPosts:
                            drItems = this.GetUnansweredPosts();
                            if ((drItems != null) && (drItems.Length > 0))
                                oDoc = GenerateOutput(drItems, false);
                            else
                                oDoc = GenerateDefaultOutput();
                            break;
                        case ReportViewType.MostActiveAuthors:
                            drItems = this.GetMostActiveAuthors();
                            if ((drItems != null) && (drItems.Length > 0))
                                oDoc = GenerateOutput(drItems);
                            else
                                oDoc = GenerateDefaultOutput();
                            break;
                        case ReportViewType.MostRecentArtifacts:
                            drItems = this.GetMostRecentArtifacts();
                            if ((drItems != null) && (drItems.Length > 0))
                                oDoc  = GenerateOutput(drItems, false);
                            else
                                oDoc  = GenerateDefaultOutput();
                            break;
                        case ReportViewType.SiteStatistics:
                            oDoc = GetSiteStatistics();
                            break;
                        default:
                            oDoc = GenerateDefaultOutput();
                            break;
                    }
                }
                else
                {
                    oDoc = GenerateDefaultOutput();
                }
               

                return oDoc;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex); //log error
                XmlDocument oError = new XmlDocument();
                oError.LoadXml(string.Format("<Error>{0}</Error>", ex.Message));
                return oError;
            }
        }

        private XmlDocument GetSiteStatistics()
        {
            SPSite site = null;
            XmlDocument tmpDoc = new XmlDocument();
            tmpDoc.LoadXml("<rows/>");

           

            try
            {
                site = SPContext.Current.Site;
                foreach (SPWeb web in _availableWebs)
                {
                    BuildSiteStats(web);
                }




                //count number of users in ASP_Net table
                string connectionString = Utilities.GetDefaultMembershipProviderConnectionString();
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using(SqlCommand com = new SqlCommand("select count(*) from dbo.aspnet_users", con))
                    {
                        con.Open();
                        int count = (int)com.ExecuteScalar();
                        //set number of users
                        _iTotalUsers = count;

                    }                   
                }
              
                //A user will not be counted unless they have logged on at least once
                //SPSecurity.RunWithElevatedPrivileges(delegate()
                //{
                //    using (SPSite ElevatedSiteCollection = new SPSite(site.ID))
                //    {
                //        using (SPWeb ElevatedSite = ElevatedSiteCollection.OpenWeb(ElevatedSiteCollection.RootWeb.ID))
                //        {
                //            _iTotalUsers = ElevatedSite.AllUsers.Count;
                //        }
                //    }
                //});
                
                
                XmlElement rowNode = tmpDoc.CreateElement("row"); //add inner element called row
                rowNode.SetAttribute("totalUsers", _iTotalUsers.ToString());
                rowNode.SetAttribute("totalSites", _iTotalSites.ToString());
                rowNode.SetAttribute("totalDiscPosts", _iTotalPosts.ToString());
                rowNode.SetAttribute("totalThreads", _iTotalThreads.ToString());
                rowNode.SetAttribute("totalArtifacts", _iTotalArtifacts.ToString());
                tmpDoc.DocumentElement.AppendChild(rowNode);
                return tmpDoc;
              
              
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                XmlDocument oError = new XmlDocument();
                oError.LoadXml(string.Format("<Error>{0}</Error>", ex.Message));
                return oError;
               
            }

        }

        /// <summary>
        /// Returns a row collection of items which have been added lately
        /// </summary>
        /// <returns></returns>
        private DataRow[] GetMostRecentArtifacts()
        {
            DataRow[] drItems;

            foreach (SPWeb web in _availableWebs)
            {
                foreach (SPList list in web.Lists)
                {
                    if (!list.Hidden)
                    {
                        if (list.BaseTemplate == SPListTemplateType.DocumentLibrary)
                        {
                            if (list.ItemCount > 0)
                            {
                                if (list.Permissions.DoesUserHavePermissions(SPRights.ViewListItems))
                                {
                                    foreach (SPListItem listItem in list.Items)
                                    {
                                        RollupItem item = null;

                                        if (listItem.DoesUserHavePermissions(SPBasePermissions.ViewListItems))
                                        {
                                            if (listItem.File != null)
                                            {
                                                if (!listItem.File.Name.EndsWith(".aspx"))
                                                {
                                                    item = PopulateItem(listItem);
                                                }
                                            }
                                            else
                                            {
                                                item = PopulateItem(listItem);
                                            }

                                            if (item != null)
                                            {
                                                this.AddItem(item);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            drItems = _dtItems.Select(string.Empty, MasterListFields.CREATED + " DESC");

            return drItems;
        }


        /// <summary>
        /// Gets a collection of rows which show the most active authors
        /// </summary>
        /// <returns></returns>
        private DataRow[] GetMostActiveAuthors()
        {
            DataRow[] drItems = null;
            DataTable dtNewRows = _dtItems.Clone();

            foreach (SPWeb web in _availableWebs)
            {

                //must elevate for anonymouse users
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite ElevatedSiteCollection = new SPSite(web.Site.ID))
                    {
                        using (SPWeb ElevatedSite = ElevatedSiteCollection.OpenWeb(web.ID))
                        {
                           
                            
                            foreach (SPList list in ElevatedSite.Lists)
                                {
                                    if (!list.Hidden)
                                    {
                                        if (list.BaseTemplate == SPListTemplateType.DocumentLibrary)
                                        {
                                            foreach (SPListItem item in list.Items)
                                            {
                                                RollupItem rollupItem;
                                                rollupItem = PopulateItem(item);
                                                this.AddItem(rollupItem);
                                            }
                                        }
                                        else if (list.BaseTemplate == SPListTemplateType.DiscussionBoard)
                                        {
                                            SPQuery query = new SPQuery();

                                            query.Query = string.Empty;
                                            query.ViewAttributes = "Scope='RecursiveAll'";
                                            this.AddPostItems(list.GetItems(query));
                                        }
                                    }
                                }
                        }
                    }
                });


            }

            string userInfo = string.Empty;

            foreach (DataRow dr in _dtItems.Select(string.Empty, MasterListFields.USERINFO + " DESC"))
            {
                if ((!dr.IsNull(MasterListFields.USERINFO)) && (dr[MasterListFields.USERINFO].ToString().Length > 0))
                {
                    if (string.Compare(dr[MasterListFields.USERINFO].ToString(), userInfo) != 0)
                    {
                        DataRow drNewRow;
                        userInfo = dr[MasterListFields.USERINFO].ToString();
                        dtNewRows.ImportRow(dr);
                        drNewRow = dtNewRows.Rows[dtNewRows.Rows.Count - 1];

                        drNewRow[MasterListFields.ENTITYCOUNT] = 1;
                    }
                    else
                    {
                        dtNewRows.Rows[dtNewRows.Rows.Count - 1][MasterListFields.ENTITYCOUNT] = int.Parse(dtNewRows.Rows[dtNewRows.Rows.Count - 1]["EntityCount"].ToString(), CultureInfo.InvariantCulture) + 1;
                    }
                }
            }

            _dtItems = dtNewRows;
            drItems = _dtItems.Select(string.Empty, MasterListFields.ENTITYCOUNT + " DESC");

            return drItems;
        }

        /// <summary>
        /// Gets a row collection of discussion posts which have not been answered
        /// </summary>
        /// <returns></returns>
        private DataRow[] GetUnansweredPosts()
        {
            DataRow[] drItems;

            foreach (SPWeb web in _availableWebs)
            {

                 //must elevate for anonymouse users
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite ElevatedSiteCollection = new SPSite(web.Site.ID))
                    {
                        using (SPWeb ElevatedSite = ElevatedSiteCollection.OpenWeb(web.ID))
                        {

                            foreach (SPList list in ElevatedSite.Lists)
                            {
                                if (!list.Hidden)
                                {
                                    if (list.BaseTemplate == SPListTemplateType.DiscussionBoard)
                                    {
                                        if (list.ItemCount > 0)
                                        {
                                            if (list.Permissions.DoesUserHavePermissions(SPRights.ViewListItems))
                                            {
                                                SPQuery query = new SPQuery();
                                                SPListItemCollection listItems;

                                                query.Query = string.Format(CultureInfo.InvariantCulture, "<Where><Eq><FieldRef Name=\"{1}\" /><Value Type=\"Integer\">{0}</Value></Eq></Where>", "0", "ItemChildCount");
                                                listItems = list.GetItems(query);

                                                foreach (SPListItem listItem in listItems)
                                                {
                                                    if (listItem.DoesUserHavePermissions(SPBasePermissions.ViewListItems))
                                                    {
                                                        RollupItem item = new RollupItem();

                                                        item = PopulateItem(listItem);

                                                        this.AddItem(item);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                });
            }

            drItems = _dtItems.Select(string.Empty, MasterListFields.CREATED + " DESC");

            return drItems;
        }

        /// <summary>
        /// Retrieves a list of the Discussion Board Threads with the most recent posts.
        /// </summary>
        /// <returns>DataRow array</returns>
        private DataRow[] GetLatestPosts()
        {
            DataRow[] drItems;


            

            foreach (SPWeb web in _availableWebs)
            {

                 //must elevate for anonymouse users
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite ElevatedSiteCollection = new SPSite(web.Site.ID))
                    {
                        using (SPWeb ElevatedSite = ElevatedSiteCollection.OpenWeb(web.ID))
                        {

                foreach (SPList list in ElevatedSite.Lists)
                {
                    if (!list.Hidden)
                    {
                        if (list.BaseTemplate == SPListTemplateType.DiscussionBoard)
                        {
                            if (list.ItemCount > 0)
                            {
                                if (list.Permissions.DoesUserHavePermissions(SPRights.ViewListItems))
                                {
                                    SPQuery query = new SPQuery();
                                    SPListItemCollection listItems;

                                    query.Query = list.Views["Subject"].Query;
                                    listItems = list.GetItems(query);

                                    foreach (SPListItem listItem in listItems)
                                    {
                                        if (listItem.DoesUserHavePermissions(SPBasePermissions.ViewListItems))
                                        {
                                            RollupItem item = new RollupItem();

                                            item = PopulateItem(listItem);

                                            this.AddItem(item);
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
                    }//end using SpWeb
                } //end using spsite
            });//end spsecurity
            }
    
            drItems = _dtItems.Select(string.Empty, MasterListFields.MODIFIED + " DESC");


            return drItems;
        }

        /// <summary>
        /// Gets and sets internal variables for various web statistics
        /// </summary>
        /// <param name="Web"></param>
        private void BuildSiteStats(SPWeb Web)
        {
            _iTotalSites++;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedSiteCollection = new SPSite(Web.Site.ID))
                {
                    using (SPWeb ElevatedSite = ElevatedSiteCollection.OpenWeb(Web.ID))
                    {

                        foreach (SPList oList in ElevatedSite.Lists)
                        {
                            if (!oList.Hidden)
                            {
                                switch (oList.BaseTemplate)
                                {
                                    case SPListTemplateType.DocumentLibrary:
                                        {
                                            _iTotalArtifacts += oList.ItemCount;
                                            break;
                                        }
                                    case SPListTemplateType.PictureLibrary:
                                        {
                                            _iTotalArtifacts += oList.ItemCount;
                                            break;
                                        }
                                    case SPListTemplateType.DiscussionBoard:
                                        {
                                            int iNumThreads = 0;
                                            int iNumPosts = 0;

                                            if (oList.BaseTemplate == SPListTemplateType.DiscussionBoard)
                                            {
                                                if (oList.Items.Count > 0)
                                                {
                                                    iNumThreads = oList.Items.Count;
                                                }

                                                iNumPosts = oList.ItemCount;
                                                iNumThreads = iNumPosts - iNumThreads;

                                                _iTotalThreads += iNumThreads;
                                                _iTotalPosts += iNumPosts;
                                            }
                                            break;
                                        }
                                }
                            }
                        }
                    }
                }
            });
        }

        /// <summary>
        /// Generates the output for the web part for Views that just need to diplay the user name and count e.g. most active authors
        /// </summary>
        /// <param name="dataRow">Array of list items</param>
        private XmlDocument GenerateOutput(DataRow[] dataRow)
        {
            SPUser melUserInfo;
            string melUserDisplayName = string.Empty;
            string melEntityDisplayName = string.Empty;

            int itemNumber = 0;

            XmlDocument tmpDoc = new XmlDocument();
            tmpDoc.LoadXml("<rows/>");

            foreach (DataRow row in dataRow)
            {
                itemNumber++;

                if (itemNumber <= _maxDisplayItems)
                {
                    melUserInfo = (SPUser)row[MasterListFields.USERINFO];
                    melUserDisplayName = melUserInfo.Name;                    

                    StringBuilder sbEntityDisplayName = new StringBuilder();
                    sbEntityDisplayName.Append(melUserDisplayName);
                    sbEntityDisplayName.Append(" (");
                    sbEntityDisplayName.Append(row[MasterListFields.ENTITYCOUNT].ToString());
                    sbEntityDisplayName.Append(")");

                    melEntityDisplayName = sbEntityDisplayName.ToString();

                    XmlElement rowNode = tmpDoc.CreateElement("row"); //add inner element called row

                    //add appropriate attrributes
                    //itemDisplayName
                    if (melEntityDisplayName != null)
                    {
                        rowNode.SetAttribute("userName", melEntityDisplayName);
                        tmpDoc.DocumentElement.AppendChild(rowNode);
                    }
                  
                }
                else
                {
                    break;
                }
            }

            return tmpDoc;
        }

        /// <summary>
        /// Generates the output for the web part
        /// </summary>
        /// <param name="dataRow">Array of list items</param>
        /// <param name="ShowItemCount">Determines whether the aggregate item count is displayed</param>
        private XmlDocument GenerateOutput(DataRow[] dataRow, bool ShowItemCount)
        {
            string melEntityDisplayName = string.Empty;
            string melEntityURL = string.Empty;
            string melEventCreated = string.Empty;
            string melUserDisplayName = string.Empty;
            string melParentEntityDisplayName = string.Empty;
            SPUser melUserInfo;
            //string melEventUserName = string.Empty;

            int itemNumber = 0;

            XmlDocument tmpDoc = new XmlDocument();
            tmpDoc.LoadXml("<rows/>");

            foreach (DataRow row in dataRow)
            {
                itemNumber++;

                if (itemNumber <= _maxDisplayItems)
                {
                    melEntityDisplayName = row[MasterListFields.ENTITYDISPLAYNAME].ToString();
                    melEntityURL = row[MasterListFields.ENTITYURL].ToString();
                    melEventCreated = row[MasterListFields.CREATED].ToString();
                    melParentEntityDisplayName = row[MasterListFields.PARENTENTITYDISPLAYNAME].ToString();
                    melUserInfo = (SPUser)row[MasterListFields.USERINFO];
                    melUserDisplayName = melUserInfo.Name;
                    
                    melEntityURL = SPEncode.UrlEncodeAsUrl(melEntityURL);
                    melEventCreated = SPEncode.HtmlEncode(melEventCreated);
                    melParentEntityDisplayName = SPEncode.HtmlEncode(melParentEntityDisplayName);
                   // melEventUserName = SPEncode.HtmlEncode(melEventUserName);
                    melUserDisplayName = SPEncode.HtmlEncode(melUserDisplayName);
                   

                    if (ShowItemCount)
                    {
                        StringBuilder sbEntityDisplayName = new StringBuilder();
                        sbEntityDisplayName.Append(melEntityDisplayName);
                        sbEntityDisplayName.Append(" (");
                        sbEntityDisplayName.Append(row[MasterListFields.ENTITYCOUNT].ToString());
                        sbEntityDisplayName.Append(")");

                        melEntityDisplayName = sbEntityDisplayName.ToString();
                    }

                    XmlElement rowNode = tmpDoc.CreateElement("row"); //add inner element called row
                    
                    //add appropriate attrributes
                    //itemDisplayName
                    if (melEntityDisplayName!= null)
                        rowNode.SetAttribute("displayName", melEntityDisplayName);
                    //item url
                    if (melEntityURL != null)
                        rowNode.SetAttribute("url", melEntityURL);
                    //createDate
                    if (melEventCreated != null)
                        rowNode.SetAttribute("createdDate", melEventCreated);
                    //user who created
                    if (melUserDisplayName != null)
                        rowNode.SetAttribute("userName", melUserDisplayName);
                    //parent display name
                    if (melParentEntityDisplayName != null)
                        rowNode.SetAttribute("parentDisplayName", melParentEntityDisplayName);

                    tmpDoc.DocumentElement.AppendChild(rowNode);

                }
                else
                {
                    break;
                }
            }

            return tmpDoc;
        }

        private XmlDocument GenerateDefaultOutput()
        {
            XmlDocument tmpDoc = new XmlDocument();
            tmpDoc.LoadXml("<rows/>");
            return tmpDoc;
        }

        private void AddItem(RollupItem item)
        {
            DataRow drItem;

            drItem = _dtItems.NewRow();
            drItem[MasterListFields.ENTITYID] = item.EntityID;
            drItem[MasterListFields.ENTITYDISPLAYNAME] = item.EntityDisplayName;
            drItem[MasterListFields.USERINFO] = item.User;
            drItem[MasterListFields.ENTITYURL] = item.EntityURL;
            drItem[MasterListFields.PARENTENTITYDISPLAYNAME] = item.ParentEntityDisplayName;
            drItem[MasterListFields.PARENTENTITYURL] = item.ParentEntityURL;
            drItem[MasterListFields.CREATED] = item.Created;
            drItem[MasterListFields.MODIFIED] = item.Modified;
            drItem[MasterListFields.ENTITYCOUNT] = item.EntityCount;

            _dtItems.Rows.Add(drItem);
        }

        //private static RollupItem PopulateItem(SPWeb web)
        //{
        //    RollupItem item = new RollupItem();

        //    item.EntityID = web.ID;
        //    item.EntityDisplayName = web.Title;
        //    item.User = web.Author;
        //    //item.EntityURL = SPUtility.GetFullUrl(web.Site, web.Url);
        //    item.EntityURL = web.Url;
        //    item.ParentEntityDisplayName = web.Site.RootWeb.Title;
        //    item.ParentEntityURL = web.Site.Url;
        //    item.Created = web.Created;
        //    item.Modified = web.LastItemModifiedDate;
        //    item.EntityCount = web.Lists.Count;

        //    return item;
        //}

        private static RollupItem PopulateItem(SPList list)
        {
            string listUrl = list.DefaultViewUrl;
            int index = listUrl.IndexOf("Lists");
            listUrl = listUrl.Substring(index);

            RollupItem item = new RollupItem();

            item.EntityID = list.ID;
            item.EntityDisplayName = list.Title;
            item.User = list.Author;
            item.EntityURL = list.ParentWeb.Url + "/" + listUrl;
            item.ParentEntityDisplayName = list.ParentWeb.Title;
            item.ParentEntityURL = SPUtility.GetFullUrl(list.ParentWeb.Site, list.ParentWeb.Url);
            item.Created = list.Created;
            item.Modified = list.LastItemModifiedDate;
            item.EntityCount = list.ItemCount;

            return item;
        }

        private static RollupItem PopulateItem(SPListItem listItem)
        {
            RollupItem item = new RollupItem();
            int userID = MasterListItem.FormatUserID(listItem[SPBuiltInFieldId.Author].ToString());
            SPUser user = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    
                    using (SPSite site = new SPSite(listItem.Web.Site.ID))
                    {
                        using (SPWeb web = site.OpenWeb(listItem.Web.ID))
                        {
                            user = web.SiteUsers.GetByID(userID);
                        }
                    }
                       
                    });
                                      

            item.User = user;
            item.ParentEntityDisplayName = listItem.ParentList.Title;
            item.ParentEntityURL = SPUtility.GetFullUrl(listItem.ParentList.ParentWeb.Site, listItem.ParentList.DefaultViewUrl);
            item.Created = Convert.ToDateTime(listItem[SPBuiltInFieldId.Created].ToString(), CultureInfo.InvariantCulture);

            item.EntityID = listItem.UniqueId;

            if ((listItem.Title == null) || (listItem.Title.Length == 0))
            {
                if ((listItem.Name == null) || (listItem.Name.Length == 0))
                {
                    // Discussion Reply
                    item.EntityDisplayName = listItem.DisplayName;

                    //The list item url for Discussion post replies add something like "/2_.00" to the url that creates an invalid link
                    //This code removes this last section of the url
                    string listItemURL = listItem.Url;
                    int index = listItemURL.LastIndexOf("/");

                    listItemURL = listItemURL.Substring(0, index);
                    item.EntityURL = listItem.Web.Url + "/" + listItemURL;

                    item.Modified = Convert.ToDateTime(listItem[SPBuiltInFieldId.Modified].ToString(), CultureInfo.InvariantCulture);
                }
                else
                {
                    // Document
                    item.EntityDisplayName = listItem.Name;
                    item.EntityURL = listItem.Web.Url + "/" + listItem.Url;
                    item.Modified = Convert.ToDateTime(listItem[SPBuiltInFieldId.Modified].ToString(), CultureInfo.InvariantCulture);
                }
            }
            else
            {
                // Discussion Thread
                item.EntityDisplayName = listItem.Title;

                item.EntityURL = listItem.Web.Url + "/" + listItem.Url;



                if (listItem[SPBuiltInFieldId.DiscussionLastUpdated] != null)
                {
                    item.Modified = Convert.ToDateTime(listItem[SPBuiltInFieldId.DiscussionLastUpdated].ToString(), CultureInfo.InvariantCulture);
                }
                else
                {
                    item.Modified = Convert.ToDateTime(listItem[SPBuiltInFieldId.Modified].ToString(), CultureInfo.InvariantCulture);
                }
            }

            return item;
        }

        private void AddPostItems(SPListItemCollection listItems)
        {
            if ((listItems != null) && (listItems.Count > 0))
            {
                foreach (SPListItem listItem in listItems)
                {
                    if (listItem.DoesUserHavePermissions(SPBasePermissions.ViewListItems))
                    {
                        RollupItem item = new RollupItem();
                        item = PopulateItem(listItem);
                        this.AddItem(item);
                    }
                }
            }
        }

        /// <summary>
        /// Build a collection of webs to use for the looping through list data
        /// </summary>
        public void CreateAvailableWebsList2()
        {

            if (!_IncludeSubsites && ((_sitesList == null) || (_sitesList.Length < 1)))
            {
                _availableWebs.Add(SPContext.Current.Web);
                return;
            }
        }

        public void CreateAvailableWebsList(SPSite Site)
        {
            if (!_IncludeSubsites && ((_sitesList == null) || (_sitesList.Length < 1)))
            {
                _availableWebs.Add(SPContext.Current.Web);
                CreateAvailableWebsList(SPContext.Current.Site, SPContext.Current.Web, 1);
            }

            if ((_sitesList != null) && (_sitesList.Length > 0))
            {
                foreach (string url in _sitesList)
                {
                    try
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            using (SPSite ElevatedSiteCollection = new SPSite(url))
                            {
                                if (ElevatedSiteCollection.ID == Site.ID)
                                {
                                    if (!_IncludeSubsites)
                                    {
                                        using (SPWeb ElevatedSite = ElevatedSiteCollection.OpenWeb(ElevatedSiteCollection.RootWeb.ID))
                                        {
                                            _availableWebs.Add(ElevatedSite);
                                            CreateAvailableWebsList(ElevatedSiteCollection, ElevatedSite, 1);
                                        }

                                    }
                                }
                                else
                                {
                                    using (SPWeb ElevatedSite = ElevatedSiteCollection.OpenWeb(ElevatedSiteCollection.RootWeb.ID))
                                    {
                                        _availableWebs.Add(ElevatedSite);
                                        CreateAvailableWebsList(ElevatedSiteCollection, ElevatedSite, 1);
                                    }
                                }
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                        throw (ex);
                    }
                }
            }
        }

        public void CreateAvailableWebsList(SPSite Site, SPWeb Web, int depth)
        {
            if (depth <= _maxSiteDepth)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite ElevatedSiteCollection = new SPSite(Site.ID))
                    {

                        using (SPWeb ElevatedSite = ElevatedSiteCollection.OpenWeb(Web.ID))
                        {
                            SPWebCollection webs = ElevatedSite.Webs;

                            foreach (SPWeb subWeb in webs)
                            {
                                _availableWebs.Add(subWeb);
                                this.CreateAvailableWebsList(Site, subWeb, depth + 1);
                            }

                        }
                    }
                });
            }
        }

        
        private static DataTable CreateDataTable()
        {
            DataTable dtItems = new DataTable("Rollup Items");
            dtItems.Locale = CultureInfo.InvariantCulture;

            dtItems.Columns.Add(MasterListFields.ENTITYID, typeof(Guid));
            dtItems.Columns.Add(MasterListFields.ENTITYDISPLAYNAME, typeof(string));
            dtItems.Columns.Add(MasterListFields.USERINFO, typeof(SPUser));
            dtItems.Columns.Add(MasterListFields.ENTITYURL, typeof(string));
            dtItems.Columns.Add(MasterListFields.PARENTENTITYDISPLAYNAME, typeof(string));
            dtItems.Columns.Add(MasterListFields.PARENTENTITYURL, typeof(string));
            dtItems.Columns.Add(MasterListFields.CREATED, typeof(DateTime));
            dtItems.Columns.Add(MasterListFields.MODIFIED, typeof(DateTime));
            dtItems.Columns.Add(MasterListFields.ENTITYCOUNT, typeof(int));

            return dtItems;
        }
       
    }

     public enum ReportViewType
        {
           
            LatestPosts,            
            LatestUnansweredDiscussionPosts,
            MostActiveAuthors,
            MostRecentArtifacts,
            SiteStatistics
           
        }
       
}
